$(function(){
  const layer = layui.layer

  // 1.获取URL携带的参数id
  const id = location.search.substring(4)
  // console.log(id)
  
  // 2.通过id发起ajax请求
  $.ajax({
    method:'GET',
    url:`http://124.223.14.236:3001/api/recipeInfo/${id}`,
    success:function(res) {
      console.log(res)
      if(!res.success) return layer.msg('获取美食失败')
      render(res.data)
    }
  })

  // 3.去除 json 中多余 \
  function pattern(a) {
    let newA = a.replaceAll('/', '');
    newA = JSON.parse(newA);
    return newA;
  }
  

  // 4.渲染数据
  function render(data){
    // 解构
    const {
      author,
      context, 
      description, 
      id, 
      img,
      raw_fu_list,
      raw_list,
      raw_tl_list,
      raw_type,
      recipe_id,
      title 
    } = data
    
    // 获取DOM元素并渲染
    $('.title-box h3').html(title)
    $('.title-box p').html(author)
    $('.show-img').attr('src',`http://124.223.14.236:3001/public/${img}`)
    $('blockquote').html(`<span
    class="txt_tart"></span>${description}<span
    class="txt_end">`)

    $('.mo h3').html(title)
    // 渲染做法步骤
    $('.recipeStep').html(context)
    // 主料 list
    renderList(raw_list, 'raw_list')
    // 辅料
    renderList(raw_fu_list, 'raw_fu_list')
    // 调料
    renderList(raw_tl_list, 'raw_tl_list')
    // type
    renderList(raw_type, 'raw_type')
  }

  // 5.渲染 食材明细 封装函数
  function renderList(raw,domId){
    let newraw = pattern(raw)

    document.querySelector(`#${domId}`).innerHTML = newraw
    .map((item) => {
      return `
      <li>
        <span class="category_s1">
            <a href="/YuanLiao/ZhongJinMianFen/" title="面粉的做法" target="_blank"><b>${item.name}</b></a>
        </span>
        <span class="category_s2">${item.num}</span>
      </li>
    `;
    })
    .join('')
  }
})